
package com.zhu.salesmanagement;

import java.util.ArrayList;
import java.util.List;

import com.dms2.salesmanagement.R;
import com.zhu.salesmanagement.common.Actions;
import com.zhu.salesmanagement.common.Log;
import com.zhu.salesmanagement.common.MyLocation;
import com.zhu.salesmanagement.common.MyLocation.LocationResult;
import com.zhu.salesmanagement.models.VisitTaskInfo;
import com.zhu.salesmanagement.network.PutCustomerData;
import com.zhu.salesmanagement.provider.SalesSettings;
import com.zhu.salesmanagement.utils.Util;
import com.zhu.salesmanagement.views.ComprehensiveEvaluationView;
import com.zhu.salesmanagement.views.ProductInfoListView;
import com.zhu.salesmanagement.views.StoreDataView;
import com.zhu.salesmanagement.views.StorePhotosView;

import android.app.Activity;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.TextView;

/**
 * 考核界面
 */
public class StoreEvaluationActivity extends Activity implements View.OnClickListener{

    public static final int UPDATE_DB = 1000;
    private VisitTaskInfo mVisitTaskInfo = null; //考核门店数据
    private ProductInfoListView mProductInfoListView = null; //考核
    private ComprehensiveEvaluationView mComprehensiveEvaluationView = null; //考评
    private StoreDataView mStoreDataView = null; //门店信息
    private StorePhotosView mStorePhotosView = null; //照片
    private ViewPager mViewPager = null;
    private List<View> mListViews = new ArrayList<View>();
    private int mCurrSelectIndex = 0;
    private int mLaseSelectIndex = 0;
    private TextView mTitleTextView = null;
    private Button mRightButton = null;
    private TextView mChenLieView = null;
    private TextView mZhongheView = null;
    private TextView mWangdianView = null;
    private TextView mPaizhaoView = null;
    private MyLocation mMyLocation = null;
    private boolean isNeedUpdate = false;
    private PutCustomerData mSyncCustomerData = null; //门店数据上传
    private FrameLayout mFrameLayout = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        Parcelable parcelable = getIntent().getParcelableExtra("info");
        mVisitTaskInfo = (VisitTaskInfo) parcelable;
        setContentView(R.layout.layout_storeevaluation_view);

        initView();
        initData();
    }

    /**
     * 初始化界面
     */
    private void initView() {
        mViewPager = (ViewPager) findViewById(R.id.vPager);
        mTitleTextView = (TextView) findViewById(R.id.storeevaluation_title);

        mFrameLayout = (FrameLayout)findViewById(R.id.body);
        findViewById(R.id.storeevaluation_back).setOnClickListener(this);
        mRightButton = (Button)findViewById(R.id.storeevaluation_stop);
        mRightButton.setOnClickListener(this);

        mChenLieView = (TextView)findViewById(R.id.storeevaluation_chenlie);
        mChenLieView.setOnClickListener(new MyOnClickListener(0));
        mZhongheView = (TextView)findViewById(R.id.storeevaluation_zhonghe);
        mZhongheView.setOnClickListener(new MyOnClickListener(1));
        mWangdianView = (TextView)findViewById(R.id.storeevaluation_wangdian);
        mWangdianView.setOnClickListener(new MyOnClickListener(2));
        mPaizhaoView = (TextView)findViewById(R.id.storeevaluation_paizhao);
        mPaizhaoView.setOnClickListener(new MyOnClickListener(3));

        findViewById(R.id.storeevaluation_shangchuan).setOnClickListener(this);
        LayoutInflater mInflater = getLayoutInflater();
        mProductInfoListView = (ProductInfoListView) mInflater.inflate(
                R.layout.productinfolist_view, null);

        mComprehensiveEvaluationView = (ComprehensiveEvaluationView) mInflater.inflate(
                R.layout.layout_cevaluation_view, null);

        mStoreDataView = (StoreDataView)mInflater.inflate(
                R.layout.layout_storedata, null);

        mStorePhotosView = (StorePhotosView)mInflater.inflate(
                R.layout.layout_storephotos, null);

        mListViews.add(mProductInfoListView);
        mListViews.add(mComprehensiveEvaluationView);
        mListViews.add(mStoreDataView);
        mListViews.add(mStorePhotosView);

        mViewPager.setAdapter(new MyPagerAdapter(mListViews));
        mViewPager.setCurrentItem(0);
        changeLightIndicator(0);
        mViewPager.setOnPageChangeListener(new MyOnPageChangeListener());
    }

    /**
     * 初始化数据
     */
    private void initData() {
        mMyLocation = new MyLocation(this, false, false);
        if(mVisitTaskInfo.mCheckinTime == null || mVisitTaskInfo.mCheckinTime.trim().length() < 1){
            mMyLocation.getLocation(locationResult, false);
        }
        mTitleTextView.setText(mVisitTaskInfo.mName);
        mProductInfoListView.initData(mVisitTaskInfo, this);
        mComprehensiveEvaluationView.initData(StoreEvaluationActivity.this);
    }

    /**
     * 按键事件处理
     */
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (!mProductInfoListView.doBack()) {
                if(isNeedUpdate){
                    setResult(RESULT_OK);
                }
                if(checkInputData(false)){
                    finish();
                }else{
                    popExitDialog();
                }
            }
            return true;
        }
        return false;
    }

    public class MyOnClickListener implements View.OnClickListener {
        private int index = 0;

        public MyOnClickListener(int i) {
            index = i;
        }

        @Override
        public void onClick(View v) {
            mViewPager.setCurrentItem(index);
        }
    };

    public class MyPagerAdapter extends PagerAdapter {
        public List<View> mListViews;

        public MyPagerAdapter(List<View> mListViews) {
            this.mListViews = mListViews;
        }

        @Override
        public void destroyItem(View arg0, int arg1, Object arg2) {
            ((ViewPager) arg0).removeView(mListViews.get(arg1));
        }

        @Override
        public void finishUpdate(View arg0) {
        }

        @Override
        public int getCount() {
            return mListViews.size();
        }

        @Override
        public Object instantiateItem(View arg0, int arg1) {
            ((ViewPager) arg0).addView(mListViews.get(arg1), 0);
            if(arg1 == 1){
                //mComprehensiveEvaluationView.initData(StoreEvaluationActivity.this);
            }else if(arg1 == 2){
                mStoreDataView.initData(StoreEvaluationActivity.this);
            }else if(arg1 == 3){
            	mStorePhotosView.initData(StoreEvaluationActivity.this, mVisitTaskInfo);
            }
            return mListViews.get(arg1);
        }

        @Override
        public boolean isViewFromObject(View arg0, Object arg1) {
            return arg0 == (arg1);
        }

        @Override
        public void restoreState(Parcelable arg0, ClassLoader arg1) {
        }

        @Override
        public Parcelable saveState() {
            return null;
        }

        @Override
        public void startUpdate(View arg0) {
        }
    }

    public class MyOnPageChangeListener implements OnPageChangeListener {

    	/**
         * 选项卡切换
         */
        @Override
        public void onPageSelected(int arg0) {
            mCurrSelectIndex = arg0;
            changeLightIndicator(mCurrSelectIndex);
            changeNormalIndicator(mLaseSelectIndex);
            changeSaveButton(mCurrSelectIndex);
            mLaseSelectIndex = mCurrSelectIndex;
        }

        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) {
        }

        @Override
        public void onPageScrollStateChanged(int arg0) {
        }
    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        switch(v.getId()){
            case R.id.storeevaluation_back :
                if(isNeedUpdate){
                    setResult(RESULT_OK);
                }
                if(checkInputData(false)){
                    finish();
                }else{
                    popExitDialog();
                }
                break;
            case R.id.storeevaluation_stop :
                saveData();
                break;
            case R.id.storeevaluation_shangchuan:
                startPutData();
            	break;
        }
    }

    /**
     * 切换选中项图片高亮
     * @param selectIndex 选中项索引
     */
    private void changeLightIndicator(int selectIndex){
        if(selectIndex == 0){
            mChenLieView.setCompoundDrawablesWithIntrinsicBounds(null, getResources().getDrawable(R.drawable.icon_cl_foucus), null, null);
        }else if(selectIndex == 1){
            mZhongheView.setCompoundDrawablesWithIntrinsicBounds(null, getResources().getDrawable(R.drawable.icon_kp_foucus), null, null);
        }else if(selectIndex == 2){
            mWangdianView.setCompoundDrawablesWithIntrinsicBounds(null, getResources().getDrawable(R.drawable.icon_wd_foucus), null, null);
        }else if(selectIndex == 3){
            mPaizhaoView.setCompoundDrawablesWithIntrinsicBounds(null, getResources().getDrawable(R.drawable.icon_po_foucus), null, null);
        }
    }

    /**
     * 切换选中项图片
     * @param selectIndex 选中项索引
     */
    private void changeNormalIndicator(int selectIndex){
        if(selectIndex == 0){
            mChenLieView.setCompoundDrawablesWithIntrinsicBounds(null, getResources().getDrawable(R.drawable.icon_cl), null, null);
        }else if(selectIndex == 1){
            mZhongheView.setCompoundDrawablesWithIntrinsicBounds(null, getResources().getDrawable(R.drawable.icon_kp), null, null);
        }else if(selectIndex == 2){
            mWangdianView.setCompoundDrawablesWithIntrinsicBounds(null, getResources().getDrawable(R.drawable.icon_wd), null, null);
        }else if(selectIndex == 3){
            mPaizhaoView.setCompoundDrawablesWithIntrinsicBounds(null, getResources().getDrawable(R.drawable.icon_po), null, null);
        }
    }

    /**
     * 切换保持按钮
     * @param selectIndex 选中项索引
     */
    private void changeSaveButton(int selectIndex){
        if(selectIndex == 0 || selectIndex == 1){
            mRightButton.setVisibility(View.VISIBLE);
        }else{
            mRightButton.setVisibility(View.INVISIBLE);
        }
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//        if (resultCode != RESULT_OK) {
//            return;
//        }
        if(mCurrSelectIndex == 3){
            mStorePhotosView.onActivityResult(requestCode, resultCode, data);
        }
    }

    public void onDestroy(){
        super.onDestroy();
        if(mStorePhotosView != null){
            mStorePhotosView.onDestroy();
        }
        if(mMyLocation != null){
            mMyLocation.destroy();
            mMyLocation = null;
        }
    }

    /**
     * 获取门店信息
     */
    public VisitTaskInfo getVisitTaskInfo(){
        return mVisitTaskInfo;
    }

    /**
     * 保存数据
     */
    public void saveData(){
    	if(mMyLocation != null && mMyLocation.isGetLocationing()){
    		Actions.toastShort(this, this.getString(R.string.getlocationnotsave));
    		return;
    	}
        checkDbData(null);
        if(mCurrSelectIndex == 0){
            mProductInfoListView.saveData(false);
        }else if(mCurrSelectIndex == 1){
            mComprehensiveEvaluationView.saveData(mVisitTaskInfo.mDbId);
            isNeedUpdate = true;
        }
    }

    /**
     * 检测及保存数据
     */
    private void checkDbData(Location location){
        if(mVisitTaskInfo.mDbId == -1){
            long id = Util.getVisitedStoreDbID(this, mVisitTaskInfo.id);
            if(id == -1){
                ContentValues values = new ContentValues();
                values.put(SalesSettings.VisitedStoresColumns.STOREID, mVisitTaskInfo.id);
                values.put(SalesSettings.VisitedStoresColumns.VISITCATEGOR, mVisitTaskInfo.type);
                Uri uri = getContentResolver().insert(
                        SalesSettings.VisitedStoresColumns.CONTENT_URI, values);
                mVisitTaskInfo.mDbId = Long.parseLong(uri.getPathSegments().get(1));
            }else{
                mVisitTaskInfo.mDbId = id;
            }
        }
        ContentValues values = new ContentValues();
        if(location != null){
            isNeedUpdate = true;
            values.put(SalesSettings.VisitedStoresColumns.CHECKIN_TIME, "" + System.currentTimeMillis());
            saveLocation(location, values);
            if(mVisitTaskInfo.mDatingTaskActualID == null){
                mVisitTaskInfo.mDatingTaskActualID = Util.getDatingTaskActualID(Util.mVerifyUserResult.id, mVisitTaskInfo.id);
            }
            values.put(SalesSettings.VisitedStoresColumns.DTASKACTUALID, mVisitTaskInfo.mDatingTaskActualID);
            getContentResolver().update(SalesSettings.VisitedStoresColumns.getContentUri(mVisitTaskInfo.mDbId, false), 
                    values, null, null);
        }else{
            if(!mVisitTaskInfo.canPut){
                values.put(SalesSettings.VisitedStoresColumns.PUTSTATUS, 1);
                values.put(SalesSettings.VisitedStoresColumns.CHECKIN_TIME, "" + System.currentTimeMillis());
                saveLocation(location, values);
                if(mVisitTaskInfo.mDatingTaskActualID == null){
                    mVisitTaskInfo.mDatingTaskActualID = Util.getDatingTaskActualID(Util.mVerifyUserResult.id, mVisitTaskInfo.id);
                }
                values.put(SalesSettings.VisitedStoresColumns.DTASKACTUALID, mVisitTaskInfo.mDatingTaskActualID);
                getContentResolver().update(SalesSettings.VisitedStoresColumns.getContentUri(mVisitTaskInfo.mDbId, false), 
                        values, null, null);
                isNeedUpdate = true;
            }
        }
    }

    /**
     * 保存地理位置
     */
    private void saveLocation(Location location, ContentValues values){
    	double lat = 0;
        double lng = 0;
        if (location != null) {
            lat = location.getLatitude();
            lng = location.getLongitude();
        }
        if(lat == 0 && lng == 0){
            Location lastLocation = Util.mGetGpsLocation.getLastLocation();
            if(lastLocation != null){
                lat = lastLocation.getLatitude();
                lng = lastLocation.getLongitude();
            }
        }
        values.put(SalesSettings.VisitedStoresColumns.CHECKIN_LAT, "" + lat);
        values.put(SalesSettings.VisitedStoresColumns.CHECKIN_LNG, "" + lng);
    }

    /**
     * 定位结果
     */
    public LocationResult locationResult = new LocationResult() {
        public void gotLocation(final Location location) {
            // Got the location!
            //if (location != null) {
            	//Actions.toastShort(StoreEvaluationActivity.this, getString(R.string.getlocationsuccesssave));
                checkDbData(location);
            //}
        }
    };

    private boolean checkInputData(boolean isShowToast){
        if(mProductInfoListView.checkInputData() && mComprehensiveEvaluationView.checkInputData()){
            return true;
        }
        if(isShowToast){
            Actions.toastShort(StoreEvaluationActivity.this, StoreEvaluationActivity.this.getString(R.string.inputdataerror));
        }
        return false;
    }

    private void startPutData(){
        if(!checkInputData(true)){
            return;
        }
        if(mSyncCustomerData == null){
            mSyncCustomerData = new PutCustomerData(this, this.getLayoutInflater(), mHandler, mFrameLayout);
        }
        mSyncCustomerData.statSync(mVisitTaskInfo.id, mVisitTaskInfo.mName);
    }

    /**
     * 上传结果返回
     */
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case PutCustomerData.SYNC_SUCCESSEND:
                    mSyncCustomerData.remoView();
                    setResult(RESULT_OK);
                    finish();
                    Actions.toastShort(StoreEvaluationActivity.this, StoreEvaluationActivity.this.getString(R.string.putdatasuccess));
                    break;
                case PutCustomerData.SYNC_FAILEDEND:
                    mSyncCustomerData.remoView();
                    Actions.toastShort(StoreEvaluationActivity.this, StoreEvaluationActivity.this.getString(R.string.putdatafail));
                    break;
            }
        }
    };

    private void popExitDialog(){
        Actions.alertShowDetails(this, getString(R.string.backclew),
                getString(R.string.backcontent),
                R.string.queding, R.string.cancel,
                new android.content.DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int arg1) {
                        finish();
                    }
                }, new android.content.DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int arg1) {

                    }
                });
    }
}
